package zsc.ruanc.practicaltraining.security.handler;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import zsc.ruanc.practicaltraining.exception.ApiException;
import zsc.ruanc.practicaltraining.mapper.Redis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SLogoutHandler extends JSONResult implements LogoutHandler {

    @Autowired
    private Redis redis;

    @Override
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Authentication authentication) {



        String headerToken = request.getHeader("token");
        System.out.println("logout header Token = " + headerToken);
        System.out.println("logout request getMethod = " + request.getMethod());


        try {
            Claim c = JWT.decode(headerToken).getClaim("id");
            int id = c.asInt();
            redis.delete(String.valueOf(id));

        } catch (Exception e) {

        }

        //
        if (!StringUtils.isEmpty(headerToken)) {
            //postMan测试时，自动假如的前缀，要去掉。

            System.out.println("authentication = " + authentication);
            SecurityContextHolder.clearContext();
        }
    }
}
